import axios from 'axios'
import { deepClone } from 'src/util/util'
import notify from "src/util/notify";

// 全局变量记录重发数
axios.defaults.retry = 2;
axios.defaults.retryDelay = 20000;

const $portal = axios.create({
  // baseURL: process.env.API,
  timeout: 60000,
  responseType: 'json',
  headers: {}
});

export default async ({ app, store, router, Vue }) => {

  // 是否表单提交
  let isFormSubmit = false, publicAction = true
  // HTTP request拦截
  $portal.interceptors.request.use(config => {
    isFormSubmit = false
    publicAction = true
    // if (config.headers['Content-Type'] !== 'multipart/form-data') {
    //   if (config.method === 'post') {
    //     config.data = {
    //       ...config.data,
    //       _t: Date.parse(new Date()) / 1000
    //     }
    //   } else if (config.method === 'get') {
    //     config.params = {
    //       _t: Date.parse(new Date()) / 1000,
    //       ...config.params
    //     }
    //   }
    // }
    // 验证申请状态，是否表单提交，表单提交统一需要弹出提示框
    if (config.headers['sub-form']) {
      isFormSubmit = true
    }
    // 验证是否需要私有处理异常
    if (config.headers['sub-pub']) {
      publicAction = false
    }
    return config
  }, error => {
    return Promise.reject(error)
  });

  // HTTPresponse拦截
  $portal.interceptors.response.use(resp => {
    let data = {};
    if (String(resp.config.url).indexOf('.txt') > -1) {
      data = resp.data
    } else {
      data = resp.data || resp.data[0]
      // if(res)
      if ([200,201].includes(data.code)) {
        if(data.data) {
          if (data.data.hasOwnProperty('token')) {
            store.commit('SET_ACCESS_TOKEN', data.data.token)
          }
          if (data.data.hasOwnProperty('signKey')) {
            store.commit('SET_SIGNKEY', data.data.signKey)
          }
        }
        if (isFormSubmit) {
          // 表单提交成功
          if (data.hasOwnProperty('message')) {
            if(data.message !== 'success'){
              notify.success(data.message)
            }else{
              notify.success(app.i18n.t('axiosSuccess'))
            }
          } else {
            notify.success(app.i18n.t('axiosSuccess'))
          }
        }
      } else {
        switch (String(data.code)) {
          case '2000':
            break;
          case '2001':
            if (publicAction) {
              notify.warning(data.message)
            }
            break;
          case '1000':
            notify.warning("未知异常")
            break;
          case '3000':
            setTimeout(() => {
              goLogin(store, router)
            }, 1500)
            break;
        }
      }
    }
    return data
  }, error => {
    let message, stop = false;
    message = app.i18n.t('wrongUrl');
    if (error.response) {
      switch (String(error.response.status)) {
        case '504':
          stop = true
          break;
        case '408':
          stop = true
          break;
        case '500':
          if (process.env.NODE_ENV === 'development') {
            message = error.response.data.message || app.i18n.t('axiosError')
          } else {
            message = app.i18n.t('axiosError')
          }
          break;
        case '401':
          let info = error.response.data.message
          publicAction = false
          break;
        case '403':
          // message = app.i18n.t('axiosError')
          router.push('/403')
          break;
        case '503':
          message = app.i18n.t('axiosError')
          break;
        case '502':
          publicAction = false
          break;
      }
    } else {
      if (String(error.message).indexOf('timeout') > -1) {
        stop = true
      }
      // else if (String(error.message) === 'Network Error') {
      //   message = app.i18n.t('NetworkWarning');
      // }
    }
      //响应编码:200-请求成功不提示信息;201-请求成功提示信息;1000-未知错误;2000-业务失败不提示信息;2001-业务失败提示信息;3000-token失效去登录

      // 异常报错-弹出提示框
      if (publicAction && ((error.response && String(error.response.url) !== '/config/behavior') || !error.response)) {
        notify.error(message)
      }
      // console.info('AXIOS', { code, message, url })

      return Promise.reject(error)

  })
  Vue.prototype.$portal = $portal;
  Vue.prototype.$axios = axios
}



// 退回到登陆页面
function goLogin (store, router) {
  // 后台返回login-first
  store.dispatch('LogOutByLoginFirst').finally(() => {
    router.push({ name: 'userLogin', params: { reload: true } });
  });
}


export { $portal }
